import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from "@/utils/storage"


Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  },
  {
    path: '/',
    name: 'layout',
    redirect: 'doshboard',
    component: () => import('../views/layout/index.vue'),
    children: [
      {
        path: '/doshboard',
        name: 'doshboard',
        component: () => import('../views/doshboard/index.vue'),
      },
      {
        path: '/article',
        name: 'article',
        component: () => import('../views/article/index.vue'),
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
    return
  }
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  next('/login')
})
//保存原型对象的Push
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
//重写push方法
VueRouter.prototype.push = function (location, res, rej) {
  if (res && rej) {
    originPush.call(this, location, res, rej)
  } else {
    originPush.call(this, location, () => { }, () => { })
  }
}
//重写replace方法
VueRouter.prototype.replace = function (location, res, rej) {
  if (res && rej) {
    originReplace.call(this, location, res, rej)
  } else {
    originReplace.call(this, location, () => { }, () => { })
  }
}
export default router
